import React from "react";
import {RequestProps} from "./type";
import {Center} from "@gluestack-ui/themed";
import {useImmer} from "use-immer";
import {ResponseData} from "@/types/utils";
import Spinkit from "react-native-spinkit";
import {useTheme} from "@/hooks";

interface State<D> {
    loading: boolean,
    data: null | D,
    isError: boolean,
}

const Request = <D extends object, P>(props: RequestProps<D, P>) => {
    const {
        children,
        api,
        params,
        onSuccess,
        onError
    } = props;
    const [{loading, isError, data}, updateData] = useImmer<State<D>>({
        loading: false,
        data: null,
        isError: false,
    });
    const {colors, layout} = useTheme();

    React.useEffect(() => {
        if (typeof api === "string") {

        } else if (typeof api === "function") {
            initiateRequest(api(params))
        }
    }, [api, params]);

    const handleSuccess = React.useCallback((data: any) => {
        onSuccess && onSuccess(data);
    }, []);


    // 发起请求
    function initiateRequest(f: Promise<ResponseData<D>>) {
        updateData(draft => {
            draft.loading = true;
        });

        f.then(res => {
            let data = (res.data ? res.data : []) as any;
            console.log("这是？", data);
            updateData(draft => {
                draft.isError = false;
                draft.data = data;
            });
            handleSuccess(data);
        }).catch(err => {
            onError && onError(err);
            updateData(draft => {
                draft.isError = true;
                draft.data = err;
            });
        }).finally(() => {
            // console.log("request组件发起请求", api, params);
            updateData(draft => {
                draft.loading = false;
            });
        });
    }


    return (
        <React.Fragment>
            {
                loading && !data
                    ?
                    <Center
                        flex={1}
                    >
                        <Spinkit isVisible={loading} size={70} type={"9CubeGrid"}
                                 color={colors.primary500}/>
                    </Center>
                    :
                    children(data, isError, loading)
            }
        </React.Fragment>
    )
};


export default Request;